 import './index.less'
import {Button, Col, Row, Select, Slider, Space} from "antd";

import {CheckOutlined, MinusOutlined, PieChartFilled, PlusOutlined} from "@ant-design/icons";
import {isEmpty} from 'lodash';
import {getAllData} from "../../api/request.ts";
import useAppState from "../../store";
import {useEffect, useState} from "react";

const ControlPanel = () => {
    const {testData, mapData, setTestData, getState, setSpinning, setCurrentMode,setThemeDateData,setCurrentTopicWord,currentTopicWord,setTopicWord} = useAppState();
    // 添加状态管理多个Select组件的值
    const [selectedValues, setSelectedValues] = useState([{theme: undefined, date: undefined}]);
    const [selectedModeValue, setSelectedModeValue] = useState('Representative_Docs_gps')
    const [selectedTopicWordValue, setSelectedTopicWordValue] = useState(undefined)
    const selectedModeOptions = [
        {value: 'Representative_Docs_gps', label: 'Representative_Docs_gps'},
        {value: 'Words_gps', label: 'Words_gps'},
    ]
    const handleModeChange = (value) => {
        setSelectedModeValue(value);
        setCurrentMode(value);
    };

    const [selectedThemeOptions, setSelectedThemeOptions] = useState([]);
    const [selectedTopicWordOptions, setSelectedTopicWordOptions] = useState([]);
    // 处理添加新的Select组
    const handleAdd = () => {
        setSelectedValues([...selectedValues, {theme: undefined, date: undefined}]);
    };

    // 处理删除最后一个Select组
    const handleRemove = () => {
        if (selectedValues.length > 1) {
            setSelectedValues(selectedValues.slice(0, -1));
        }
    };

    // 处理主题选择变化
    const handleThemeChange = (index, value) => {
        const newValues = [...selectedValues];
        newValues[index].theme = value;
        // 清空对应的日期选择
        newValues[index].date = undefined;
        setSelectedValues(newValues);
    };

    // 处理日期选择变化
    const handleDateChange = (index, value) => {
        const newValues = [...selectedValues];
        newValues[index].date = value;
        setSelectedValues(newValues);
    };
    // 获取日期选项（根据当前主题）
    const getDateOptions = (theme) => {
        if (!theme) return [];
        else if(!mapData[theme]){
            const themes = Object.keys(mapData);
            const allItems = themes.reduce((acc, theme) => {
                return acc.concat(Object.keys(mapData[theme]));
            }, []);

            const uniqueItems = [...new Set(allItems)];
            const result = uniqueItems.map(item => ({
                value: item,
                label: item // 如果label需要和value相同
            }));
            result.push({
                value: "All",
                label: "All"
            })
            return result;
        }
        const tempData=Object.keys(mapData[theme]).map(date => ({
            value: date,
            label: date
        }));
        tempData.push({
            value: "All",
            label: "All"
        })
        return tempData;
    };
    useEffect(() => {
        if (isEmpty(mapData)) return;
        const tempThemeData = Object.keys(mapData).map(item => ({value: item, label: item}));
        setSelectedTopicWordOptions(JSON.parse(JSON.stringify(tempThemeData)));
        tempThemeData.push({
            value: "All",
            label: "All"
        })
        setSelectedThemeOptions(tempThemeData);
        const defaultTheme=Object.keys(mapData)[0],defaultDate=Object.keys(mapData[defaultTheme])[0];
        setSelectedTopicWordValue(defaultTheme);
        setCurrentTopicWord(defaultTheme);
        setSelectedValues([{theme: defaultTheme, date: defaultDate}])
        setThemeDateData([{theme: defaultTheme, dates: [defaultDate]}])
    }, [mapData]);
    const submit = () => {
        const tempData=[];
        const themes=Object.keys(mapData);
        selectedValues.forEach(item=>{
            if(item.theme=="All"&&item.date==="All"){
                themes.forEach(theme=>{
                    const dates=Object.keys(mapData[theme]);
                    dates.forEach(date=>{
                        tempData.push(
                        {theme: theme, date: date})
                    })
                })
            }else if(item.theme==="All"){
                themes.forEach(theme=>{
                    const dates=Object.keys(mapData[theme]);
                    if(dates.includes(item.date)){
                        tempData.push(
                            {theme: theme, date: item.date})
                    }
                })
            }else if(item.date==="All"){
                const dates=Object.keys(mapData[item.theme]);
                dates.forEach(date=>{
                    tempData.push({
                        theme:item.theme,date:date
                    })
                })
            }else tempData.push(
                {theme: item.theme, date: item.date})
        })
        const groupedByTheme = Object.values(
            tempData.reduce((acc, { theme, date }) => {
                acc[theme] = acc[theme] || { theme, dates: new Set() }
                acc[theme].dates.add(date)
                return acc
            }, {})
        )
            .map(group => ({
                ...group,
                dates: Array.from(group.dates)
            }))
            // 新增：按数字值排序
            .sort((a, b) => parseInt(a.theme) - parseInt(b.theme))
        setThemeDateData(groupedByTheme)
    }
    const fetchData = async (selectedTopicWordValue) => {
        try {
            // setSpinning(true);
            // 发送请求并等待响应
            const {topicWordEvolution} = await getAllData(false,{topic:selectedTopicWordValue});
            setTopicWord(topicWordEvolution);
            // setSpinning(false);
        } catch (error) {
            console.error("请求失败:", error);
        }
    };
    const handleConfirm=()=>{
        fetchData(selectedTopicWordValue);
        setCurrentTopicWord(selectedTopicWordValue);
    }
    useEffect(() => {
        console.log(currentTopicWord, '更新了');
    }, [currentTopicWord]); // 监听 testData 的变化
    return (
        <div className="ControlPanel">
                <div className={"title"}>Control panel</div>
                <div className={"ControlPanelTop"}>
                    <Button type={"primary"} onClick={submit} style={{marginBottom: 8, width: "100%"}}>Submit</Button>
                    <div style={{marginBottom: 8}}>Switch_Mode:</div>
                    <Select
                        style={{width: '100%'}}
                        value={selectedModeValue}
                        showSearch
                        placeholder="Select"
                        options={selectedModeOptions}
                        onChange={handleModeChange}
                        filterOption={(input, option) =>
                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                        } // 自定义搜索逻辑
                    />
                </div>
                <div className={"ControlPanelMiddle"}>
                    <div style={{marginBottom: 8}}>Topic_Date:</div>
                    <Row>
                        {/* 动态渲染Select组 */}
                        {selectedValues.map((item, index) => (
                            <Space
                                key={index}
                                style={{width: "100%", marginBottom: "8px"}}
                            >
                                <Space.Compact style={{width: '100%'}}>
                                    <Select
                                        style={{width: '50%'}}
                                        showSearch
                                        placeholder="Topic"
                                        value={item.theme}
                                        options={selectedThemeOptions}
                                        onChange={(value) => handleThemeChange(index, value)}
                                        filterOption={(input, option) =>
                                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                        }
                                    />
                                    <Select
                                        style={{width: '50%'}}
                                        showSearch
                                        placeholder="Date"
                                        value={item.date}
                                        options={getDateOptions(item.theme)}
                                        onChange={(value) => handleDateChange(index, value)}
                                        filterOption={(input, option) =>
                                            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                        }
                                    />
                                </Space.Compact>
                            </Space>
                        ))}
                        <Space>
                            <Button
                                type="primary"
                                icon={<PlusOutlined/>}
                                onClick={handleAdd}
                            >
                            </Button>
                            <Button
                                danger
                                icon={<MinusOutlined/>}
                                onClick={handleRemove}
                                disabled={selectedValues.length === 1} // 只剩一个时禁用
                            >
                            </Button>
                        </Space>
                    </Row>
                </div>
                <div className={"ControlPanelBottom"}>
                    <div style={{marginBottom:8,marginTop:40}}>Topic_Word:</div>
                    <Space  style={{width: "100%"}}>
                        <Select
                            style={{width: '100%'}}
                            showSearch
                            placeholder="Topic"
                            value={selectedTopicWordValue}
                            options={selectedTopicWordOptions}
                            onChange={(value) => setSelectedTopicWordValue(value)}
                            filterOption={(input, option) =>
                                (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                            }
                        ></Select>
                        <Button
                            type="primary"
                            icon={<CheckOutlined />}
                            onClick={handleConfirm}
                        >
                        </Button>
                    </Space>
                </div>
            </div>
    )
}
export default ControlPanel;
